<template>
  <div class="reader-container">
    <!-- 搜索和操作栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" @submit.prevent>
        <el-form-item>
          <el-input
            v-model="searchForm.username"
            placeholder="读者姓名"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="searchForm.cardId"
            placeholder="借书证号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border style="width: 100%" v-loading="loading">
      <el-table-column prop="cardId" label="借书证号" width="120" />
      <el-table-column prop="username" label="姓名" width="100" />
      <el-table-column prop="sex" label="性别" width="80">
        <template #default="scope">
          {{ scope.row.sex === 0 ? "男" : "女" }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="120" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
            {{ scope.row.status === 0 ? "正常" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="注册时间" width="180" />
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="scope">
          <el-button-group>
            <el-button type="primary" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button
              :type="scope.row.status === 0 ? 'danger' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 0 ? "禁用" : "启用" }}
            </el-button>
            <el-button type="info" @click="handleViewBooks(scope.row)">
              借阅记录
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        status-icon
      >
        <el-form-item label="姓名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 借阅记录对话框 -->
    <el-dialog title="借阅记录" v-model="borrowDialogVisible" width="800px">
      <el-table :data="borrowRecords" border style="width: 100%">
        <el-table-column prop="bookName" label="图书名称" />
        <el-table-column prop="borrowDate" label="借阅时间" width="180" />
        <el-table-column prop="returnDate" label="归还时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'warning' : 'success'">
              {{ scope.row.status === 1 ? "借阅中" : "已归还" }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { Search, Refresh, Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getReaderList,
  addReader,
  updateReader,
  getBorrowRecords,
  updateReaderStatus,
} from "../apis/reader";

// 搜索表单
const searchForm = ref({
  username: "",
  cardId: "",
});

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref("add");
const dialogTitle = computed(() =>
  dialogType.value === "add" ? "新增读者" : "编辑读者"
);

// 借阅记录对话框
const borrowDialogVisible = ref(false);
const borrowRecords = ref([]);

// 表单相关
const formRef = ref(null);
const form = ref({
  cardId: "",
  username: "",
  sex: 0,
  phone: "",
  email: "",
});

// 表单校验规则
const rules = {
  username: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
};

// 获取读者列表
const getReaders = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      username: searchForm.value.username,
      cardId: searchForm.value.cardId,
    };
    const res = await getReaderList(params);
    tableData.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  getReaders();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    username: "",
    cardId: "",
  };
  handleSearch();
};

// 新增
const handleAdd = () => {
  dialogType.value = "add";
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row) => {
  dialogType.value = "edit";
  form.value = { ...row };
  dialogVisible.value = true;
};

// 切换状态
const handleToggleStatus = (row) => {
  const action = row.status === 0 ? "禁用" : "启用";
  ElMessageBox.confirm(`确认${action}该读者?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await updateReaderStatus(row.readerId, row.status === 0 ? 1 : 0);
    ElMessage.success(`${action}成功`);
    getReaders();
  });
};

// 查看借阅记录
const handleViewBooks = async (row) => {
  borrowDialogVisible.value = true;
  const res = await getBorrowRecords(row.readerId);
  borrowRecords.value = res.data;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      if (dialogType.value === "add") {
        await addReader(form.value);
      } else {
        await updateReader(form.value);
      }
      ElMessage.success(dialogType.value === "add" ? "添加成功" : "更新成功");
      dialogVisible.value = false;
      getReaders();
    }
  });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.value = {
    username: "",
    sex: 0,
    phone: "",
    email: "",
  };
};

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  getReaders();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getReaders();
};

onMounted(() => {
  getReaders();
});
</script>

<style scoped>
.reader-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
